/*
 * GeneTrees.cpp
 *
 *  Created on: Mar 23, 2012
 *      Author: pickrell
 */


#include "ManyTrees.h"
#include "CmdLine.h"
using namespace std;


void printopts(){
        cout << "Options:\n";
        cout << "-i [file name] input file\n";
        cout << "-o [file name] output file\n";
        cout << "-b [file name] breakpoints file\n";
        cout << "-bp [N] make N intervals in coalescent time\n";
        cout << "-se [N] calculate standard errors by bootstrapping N times\n";
        cout << "-struct [N] structured from bin N\n";
        cout << "-print print trees\n";
        cout << "\n";
}

string infile;
string outfile;
string bfile;
bool ses;
int bootN;
bool structure = false;
int structbin = 0;
bool setbp = true;
int nbp = 10;
bool print = false;

int main(int argc, char *argv[]){

	const gsl_rng_type * T;
	gsl_rng * r;
	gsl_rng_env_setup();
	T = gsl_rng_ranlxs2;
	r = gsl_rng_alloc(T);
	int seed = (int) time(0);
	gsl_rng_set(r, seed);
	PhyloPop_params p;
    CCmdLine cmdline;
    if (cmdline.SplitLine(argc, argv) < 1){
        printopts();
        exit(1);
    }
    if (cmdline.HasSwitch("-i")) infile = cmdline.GetArgument("-i", 0).c_str();
    else{
        printopts();
        exit(1);
    }
    if (cmdline.HasSwitch("-o")) outfile = cmdline.GetArgument("-o", 0).c_str();
     else{
         printopts();
         exit(1);
     }
    if (cmdline.HasSwitch("-bp")){
    	nbp = atoi(cmdline.GetArgument("-bp", 0).c_str());
    	setbp = true;
    }
    if (cmdline.HasSwitch("-b")) bfile = cmdline.GetArgument("-b", 0).c_str();
    if (cmdline.HasSwitch("-se")) {
    	ses = true;
    	bootN = atoi(cmdline.GetArgument("-se", 0).c_str());
    }
    if (cmdline.HasSwitch("-struct")) {
    	structure = true;
    	structbin = atoi(cmdline.GetArgument("-struct", 0).c_str());
    }
    if (cmdline.HasSwitch("-print")) print = true;
    ManyTrees trees(infile, &p);
    if (setbp){
    	//cout <<"here\n"; cout.flush();
    	trees.set_bpoints(nbp);
    	//cout << "not here\n"; cout.flush();
    }
    else{
    	trees.read_bpoints(bfile);
    }
    trees.init_popsizes();
    trees.optim_all_popsizes();
    if (!ses) trees.print_state(outfile);
    else trees.bootstrap_and_print(outfile, bootN, r);
    if (structure){
    	trees.init_structure(structbin, r);
    	trees.iterate_optim_all_struct();
    	trees.print_struct_state(outfile+".struct");
    }
    if (print) trees.print_all_trees(outfile);
    return 0;
}
